#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "mpi.h"

/****************************************************
 * \file test_scatter.c
 * \author James Edmondson
 * \brief Scatters a list of ranks to each rank of
 *        MPI_COMM_WORLD from rank 0.
 ****************************************************/

int
main(int argc, char **argv)
{
	int size, rank;

	int * sendbuf;
	int recvbuf = 4; 
	int i = 0;
	int success = 1;
	
	MPI_Init(&argc, &argv);
	
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	printf("Size %d, Rank %d\n",size,rank);

	sendbuf = (int *)malloc(sizeof(int) * size);
	
	for( i = 0; i < size; i++ )
	{
		sendbuf[i] = i;
	}
	
	if( rank == 0 )
	{
		int * list = (int *)malloc(size * sizeof(int));
		printf("SCATTER ROOT BEFORE: recvbuf=%d\n",recvbuf);
		MPI_Scatter(sendbuf,1,MPI_INT,list, 1, MPI_INT, 0, MPI_COMM_WORLD);
		printf("SCATTER ROOT AFTER: recvbuf=%d\n",recvbuf);
		success = success & (recvbuf == 4);
	}
	else 
	{
		recvbuf = 1;
		printf("SCATTER BEFORE: recvbuf=%d\n",recvbuf);
		MPI_Scatter(sendbuf,1,MPI_INT, &recvbuf, 1, MPI_INT, 0, MPI_COMM_WORLD);
		printf("SCATTER AFTER: recvbuf=%d\n",recvbuf);
		success = success & (recvbuf == rank);
	}
	
	
	MPI_Finalize();
	if (success == 1) {
		printf("SUCCESS\n");
	}
	return 0;
}

